import {register, login, getCustomer, sms} from '../services/api';
import Taro from "@tarojs/taro";

export default {
  namespace: 'customer',

  state: {
    item: {},
  },

  effects: {
    * register({payload}, {call}) {
      const result = yield call(register, payload);
      if (result && result.code === 0) {
        Taro.setStorageSync('sys_user_info', result.data);
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 1000,
        });

        setTimeout(() => {
          Taro.navigateBack();
        }, 1000);
      } else {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 1000,
        })
      }
    },

    * login({payload}, {call}) {
      const result = yield call(login, payload);
      if (result && result.code === 0) {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 1000,
        });
        setTimeout(() => {
          Taro.navigateBack();
        }, 1000);
      } else {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 1000,
        })
      }
    },

    * get({payload}, {call, put}) {
      const result = yield call(getCustomer, payload);
      if (result && result.code === 0) {
        yield put({
          type: 'save',
          payload: {
            item: result.data,
          },
        });
      }
    },

    * sms({payload}, {call}) {
      const result = yield call(sms, payload);
      if (result && result.code === 0) {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 1000,
        });
      }
    },
  },

  reducers: {
    save(state, {payload}) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
